<template>
  <div class="merchant-management">
    <h2>商家管理</h2>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="商品管理" name="product-management">
        <div class="product-management">
          <h3>商品列表</h3>
          <div class="product-header">
            <el-button type="success" @click="showAddProductDialog"
              >添加商品</el-button
            >
          </div>
          <el-table :data="productsList" style="width: 100%">
            <el-table-column prop="shop_name" label="商品名称" />
            <el-table-column prop="shop_price" label="价格" />
            <el-table-column label="商品图片">
              <template slot-scope="scope">
                <img
                  :src="getImageUrl(scope.row.shop_img)"
                  alt="商品图片"
                  class="product-image"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="editProduct(scope.row)" type="primary"
                  >修改</el-button
                >
                <el-button @click="deleteProduct(scope.row.id)" type="danger"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 添加商品对话框 -->
        <el-dialog title="添加商品" :visible.sync="addProductDialogVisible">
          <el-form :model="newProduct">
            <el-form-item label="商品名称">
              <el-input v-model="newProduct.shop_name"></el-input>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model.number="newProduct.shop_price"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="newProduct.shop_description"></el-input>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="upload-demo"
                drag
                action=""
                :on-change="handleImageChange"
                :show-file-list="true"
                :file-list="uploadedFiles"
                :on-remove="handleRemove"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addProductDialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="addProduct">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 修改商品对话框 -->
        <el-dialog title="修改商品" :visible.sync="editProductDialogVisible">
          <el-form :model="currentProduct">
            <el-form-item label="商品名称">
              <el-input v-model="currentProduct.shop_name"></el-input>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model.number="currentProduct.shop_price"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="currentProduct.shop_description"></el-input>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="upload-demo"
                drag
                action=""
                :on-change="handleImageChange"
                :show-file-list="false"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editProductDialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="updateProduct">确 定</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane label="待发货订单" name="pending-orders">
        <div>
          <h3>待发货订单列表</h3>
          <div v-if="pendingOrders.length === 0" class="no-orders">
            没有待发货的订单。
          </div>
          <div v-else>
            <ul class="order-list">
              <li
                v-for="order in pendingOrders"
                :key="order.id"
                class="order-item"
              >
                <div class="order-header">
                  <span class="order-id">订单号: {{ order.id }}</span>
                  <span class="order-total"
                    >总价: {{ order.total_price }} 元</span
                  >
                </div>
                <ul class="item-list">
                  <li
                    v-for="item in order.order_items"
                    :key="item.product_id"
                    class="item"
                  >
                    <span class="item-name"
                      >商品名称: {{ getProductName(item.product_id) }}</span
                    >
                    <span class="item-quantity">数量: {{ item.quantity }}</span>
                    <span class="item-price"
                      >单价: {{ getProductPrice(item.product_id) }} 元</span
                    >
                    <img
                      :src="getImageUrl(getProductImage(item.product_id))"
                      alt="商品图片"
                      class="item-image"
                    />
                  </li>
                </ul>
                <el-button
                  type="primary"
                  @click="shipOrder(order.id)"
                  class="ship-button"
                  >发货</el-button
                >
              </li>
            </ul>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="已发货订单" name="shipped-orders">
        <div>
          <h3>已发货订单列表</h3>
          <div v-if="shippedOrders.length === 0" class="no-orders">
            没有已发货的订单。
          </div>
          <div v-else>
            <ul class="order-list">
              <li
                v-for="order in shippedOrders"
                :key="order.id"
                class="order-item"
              >
                <div class="order-header">
                  <span class="order-id">订单号: {{ order.id }}</span>
                  <span class="order-total"
                    >总价: {{ order.total_price }} 元</span
                  >
                </div>
                <ul class="item-list">
                  <li
                    v-for="item in order.order_items"
                    :key="item.product_id"
                    class="item"
                  >
                    <span class="item-name"
                      >商品名称: {{ getProductName(item.product_id) }}</span
                    >
                    <span class="item-quantity">数量: {{ item.quantity }}</span>
                    <span class="item-price"
                      >单价: {{ getProductPrice(item.product_id) }} 元</span
                    >
                    <img
                      :src="getImageUrl(getProductImage(item.product_id))"
                      alt="商品图片"
                      class="item-image"
                    />
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="已完成订单" name="completed-orders">
        <div>
          <h3>已完成订单列表</h3>
          <div v-if="completedOrders.length === 0" class="no-orders">
            没有已完成的订单。
          </div>
          <div v-else>
            <ul class="order-list">
              <li
                v-for="order in completedOrders"
                :key="order.id"
                class="order-item"
              >
                <div class="order-header">
                  <span class="order-id">订单号: {{ order.id }}</span>
                  <span class="order-total"
                    >总价: {{ order.total_price }} 元</span
                  >
                </div>
                <ul class="item-list">
                  <li
                    v-for="item in order.order_items"
                    :key="item.product_id"
                    class="item"
                  >
                    <span class="item-name"
                      >商品名称: {{ getProductName(item.product_id) }}</span
                    >
                    <span class="item-quantity">数量: {{ item.quantity }}</span>
                    <span class="item-price"
                      >单价: {{ getProductPrice(item.product_id) }} 元</span
                    >
                    <img
                      :src="getImageUrl(getProductImage(item.product_id))"
                      alt="商品图片"
                      class="item-image"
                    />
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      activeTab: "pending-orders",
      pendingOrders: [],
      uploadedFiles: [],
      shippedOrders: [],
      completedOrders: [],
      productsList: [],
      addProductDialogVisible: false,
      editProductDialogVisible: false,
      newProduct: {
        shop_name: "",
        shop_price: 0,
        shop_description: "",
        shop_img: null,
      },
      currentProduct: {},
    };
  },
  methods: {
    fetchProducts() {
      // 获取商品列表
      axios
        .get("/orders/getOrderBystatus", { params: { status: 1 } }) // 假设状态1为商品状态
        .then((response) => {
          if (response.data.code === 200) {
            this.productsList = response.data.data; // 假设返回的数据结构
          } else {
            this.$message.error("获取商品失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取商品失败:", error);
          this.$message.error("获取商品失败，请重试。");
        });
    },
    fetchPendingOrders() {
      const customer_id = localStorage.getItem("userId");
      if (!customer_id) {
        this.$message.error("用户未登录或ID不存在");
        return;
      }
      // 获取待发货订单
      axios
        .get("/orders/getOrderBystatus", { params: { status: 2 } })
        .then((response) => {
          if (response.data.code === 200) {
            const orders = response.data.data;
            this.pendingOrders = orders.filter(
              (order) => order.status === "待发货"
            );
          } else {
            this.$message.error("获取待发货订单失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取待发货订单失败:", error);
          this.$message.error("获取待发货订单失败，请重试。");
        });

      // 获取已发货订单
      axios
        .get("/orders/getOrderBystatus", { params: { status: 3 } })
        .then((response) => {
          if (response.data.code === 200) {
            const orders = response.data.data;
            this.shippedOrders = orders.filter(
              (order) => order.status === "已发货"
            );
          } else {
            this.$message.error("获取已发货订单失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取已发货订单失败:", error);
          this.$message.error("获取已发货订单失败，请重试。");
        });

      // 获取已完成订单
      axios
        .get("/orders/getOrderBystatus", { params: { status: 5 } })
        .then((response) => {
          if (response.data.code === 200) {
            const orders = response.data.data;
            this.completedOrders = orders.filter(
              (order) => order.status === "已完成"
            );
          } else {
            this.$message.error("获取已完成订单失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取已完成订单失败:", error);
          this.$message.error("获取已完成订单失败，请重试。");
        });

      this.fetchProductDetails(); // 获取产品详情
    },
    fetchProductDetails() {
      axios
        .get("/GetProductsList") // 获取所有商品信息
        .then((response) => {
          if (response.data.code === 200) {
            this.productsList = response.data.data;
          } else {
            console.error("获取商品数据失败:", response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取商品数据失败:", error);
        });
    },
    getProductName(productId) {
      const product = this.productsList.find((p) => p.id === productId);
      return product ? product.shop_name : "未知商品";
    },
    getProductPrice(productId) {
      const product = this.productsList.find((p) => p.id === productId);
      return product ? product.shop_price : 0;
    },
    getProductImage(productId) {
      const product = this.productsList.find((p) => p.id === productId);
      return product ? product.shop_img : "";
    },
    getImageUrl(base64String) {
      return `data:image/jpeg;base64,${base64String}`; // 将二进制数据转换为可用的图片 URL
    },
    shipOrder(orderId) {
      // 调用接口更新订单状态为3
      axios
        .put(`/orders/${orderId}/status?status=3`) // 发货操作
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("订单已发货！");
            this.fetchPendingOrders(); // 重新获取待发货和已发货订单
          } else {
            this.$message.error("发货失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("发货失败:", error);
          this.$message.error("发货失败，请重试。");
        });
    },
    showAddProductDialog() {
      this.addProductDialogVisible = true;
      this.newProduct = {
        shop_name: "",
        shop_price: 0,
        shop_description: "",
        shop_img: null,
      };
    },
    addProduct() {
      const formData = new FormData();
      formData.append("shop_img", this.newProduct.shop_img);
      formData.append("shop_name", this.newProduct.shop_name);
      formData.append("shop_price", this.newProduct.shop_price);
      formData.append("shop_description", this.newProduct.shop_description);
      formData.append("shop_id", 2); // 假设店铺ID为1

      axios
        .post("/AddProduct", formData)
        .then((response) => {
          console.log("添加商品数据", response);
          if (response.data.code === 200) {
            this.$message.success("商品添加成功");
            this.addProductDialogVisible = false;
            this.fetchProductDetails();
          } else {
            this.$message.error("添加商品失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("添加商品失败:", error);
          this.$message.error("添加商品失败，请重试。");
        });
    },
    editProduct(product) {
      this.currentProduct = { ...product };
      this.editProductDialogVisible = true;
    },
    updateProduct() {
      axios
        .post("/UpdProduct", this.currentProduct)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("商品修改成功");
            this.editProductDialogVisible = false;
            this.fetchProductDetails();
          } else {
            this.$message.error("修改商品失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("修改商品失败:", error);
          this.$message.error("修改商品失败，请重试。");
        });
    },
    deleteProduct(productId) {
      this.$confirm("确定要删除该商品吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 修改为使用 params 传递参数
          axios
            .post(`/DelProductById`, null, { params: { id: productId } })
            .then((response) => {
              if (response.data.code === 200) {
                this.$message.success("商品删除成功");
                this.fetchProductDetails();
              } else {
                this.$message.error("删除商品失败: " + response.data.msg);
              }
            })
            .catch((error) => {
              console.error("删除商品失败:", error);
              this.$message.error("删除商品失败，请重试。");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    handleImageChange(file) {
      this.newProduct.shop_img = file.raw; // 保存上传的文件
      this.uploadedFiles.push(file); // 将上传的文件添加到文件列表
      this.$message.success("商品图片上传成功！"); // 添加成功提示
    },

    handleRemove(file) {
      const index = this.uploadedFiles.indexOf(file);
      if (index !== -1) {
        this.uploadedFiles.splice(index, 1); // 从文件列表中移除文件
      }
    },
  },
  mounted() {
    this.fetchPendingOrders(); // 组件挂载时获取待发货、已发货和已完成订单
    this.fetchProducts(); // 组件挂载时获取商品列表
  },
};
</script>

<style scoped>
.order-list {
  list-style-type: none;
  padding: 0;
}

.order-item {
  background-color: #fff;
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.order-id {
  font-weight: bold;
}

.order-total {
  color: #ff5722;
  /* 价格颜色 */
}

.item-list {
  list-style-type: none;
  padding: 0;
}

.item {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
  border-bottom: 1px solid #e0e0e0;
}

.item-name {
  flex: 1;
}

.item-quantity,
.item-price {
  margin-left: 10px;
}

.item-image {
  max-width: 50px;
  /* 设置图片宽度 */
  height: auto;
  margin-left: 10px;
  /* 图片与文本之间的间距 */
}

.no-orders {
  color: #999;
  font-style: italic;
}

.ship-button {
  margin-top: 10px;
}

.product-management {
  display: flex;
  flex-direction: column;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-image {
  max-width: 50px; /* 设置商品图片宽度 */
  height: auto;
}
</style>
